<?php
class Core_Business_Zone extends Core_Business_Abstract {
	private $_zipcode;
	private $_commune;
	private $_departement;
	private $_dep;
	private $_cpinsee;
	
	public function getZipcode() {return $this->_zipcode;}
	public function setZipcode($value) {$this->_zipcode=$value;}
	
	public function getCommune() {return $this->_commune;}
	public function setCommune($value) {$this->_commune = $value;}
	
	public function getDepartement() {return $this->_departement;}
	public function setDepartement($value) {$this->_departement=$value;}

	public function getDep() {return $this->_dep;}
	public function setDep($value) {$this->_dep=$value;}
	
	public function getInsee() {return $this->_cpinsee;}
	public function setInsee($value) {$this->_cpinsee=$value;}
	
	public static function getAllDepatement() {
		$map = new Core_Data_Mappers_Zone();
		$query = new Zend_Db_Select($map->getDbTable()->getAdapter());
		$query->from("departement",array("departement","departementcode"))
			  ->order("departement asc");
		$query->assemble();
		$rows = $map->getDbTable()->getAdapter()->fetchAll($query);
		if (isset($rows) && count($rows)>0){
			foreach ($rows as $row) {
				$collection[] = $map->map($row);
			}
		}
		return $collection;
	}
	
	public static function getByZipCode($zipcode) {
		$map = new Core_Data_Mappers_Zone();
		return $map->find($zipcode);
	} 
	
	public static function getByDep($dep) {
		$map = new Core_Data_Mappers_Zone();
		$dep = is_array($dep) ? $dep : array($dep);
		$communes = $map->fetchAll(array("departementcode in (?)"=>$dep));
		return $communes;
	}
	
	public static function getByCodeinsee($codeinsee) {
		$map = new Core_Data_Mappers_Zone();
		$codeinsee = is_array($codeinsee) ? $codeinsee : array($codeinsee);
		
		$communes = $map->fetchAll(array("codeinsee in (?)"=>$codeinsee));
		return current($communes);
		
	}
	
	public static function searchZone($filter) {
		$cfilter=array();
		if(preg_match("`^(\d){2,2}$`", $filter)>0) {
			$cfilter = "departementcode = ?";
		}
		if(preg_match("`^(\d){2,5}$`", $filter)>0){
			$filter .= '%';
			$cfilter = "zipcode like ?";
		}
		if(preg_match("`^(\w)+$`", $filter)>0) {
			$filter .= '%';
			$cfilter = "departement like ? or commune like ?";
		}
		$map = new Core_Data_Mappers_Zone();
		$query = $map->getDbTable()->select()
				->where($cfilter,$filter)
				->order("commune");
		$communes = $map->fetchQuery($query);
		return $communes;
	}
}